package com.yandex.yandexfotki.activities;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;

import utils.HTTPMethod;
import utils.ServerRequest;
import utils.YaPreferences;
import utils.YandexAPI;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import fragments.AddOptionsFragment;
import fragments.CreateAlbumFragment;
import fragments.InternetLockFragment;
import fragments.PreviewPhotoFragment;
import fragments.ProgressDialogFragment;
import fragments.TakePhotoFragment;

//{"access_token": "ed465d1379444db5b7742a2d8639ef24", "token_type": "bearer"}
//id ae90b3773cfa4fcda2d275d0c021c68c
//pass b351809391a94225b6e0d74c2f1952ca
public class StartActivity extends FragmentActivity {

	
	
	public void showDialog() {
	   
	    // DialogFragment.show() will take care of adding the fragment
	    // in a transaction.  We also want to remove any currently showing
	    // dialog, so make our own transaction and take care of that here.
	    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
	    Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");//findFragmentByTag("dialog");
	    if (prev != null) {
	        ft.remove(prev);
	    }
//	    ft.addToBackStack(null);

	    // Create and show the dialog.
	    DialogFragment newFragment = new ProgressDialogFragment();//MyDialogFragment.newInstance(mStackLevel);
	    newFragment.show(ft, "dialog");
//	    newFragment.show(ft,"dialog");
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
//		if(getIntent().getData().getQueryParameter("access_token")!=null){
//			Log.d("yandex","ok!");
//		}
	}

	public YandexAPI getYapi() {
		return yapi;
	}

	public void setYapi(YandexAPI yapi) {
		this.yapi = yapi;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		yaPrefs = new YaPreferences(this);
		startApp();
//		GetServiseDocumentTask getServiseDocumentTask = new GetServiseDocumentTask();
//		getServiseDocumentTask.execute();
//		AuthorizationTask at = new AuthorizationTask();
//		at.execute();
//		startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://oauth.yandex.ru/authorize?response_type=token&client_id=ed49b67ef91547279d33378569039264&display=popup")));
	}
	
	private String getTokenFromUri(Uri data) {
		String[] splitedUri = data.toString().split("#");
		String[] splitedAnchor = splitedUri[1].split("&");
		String[] accessTokenParts = splitedAnchor[0].split("=");
		return accessTokenParts[1];
	}
	
	private void startApp() {
		if(getIntent().getData()!=null){
			Uri data = getIntent().getData();
			yaPrefs.setToken(getTokenFromUri(data));
			//Log.d("yandex",getTokenFromUri(data));
		}
		if(yaPrefs.hasToken()){
			yapi = new YandexAPI(yaPrefs.getToken());
			if(checkConnection()){
				showDialog();
				GetServiseDocumentTask getServiseDocumentTask = new GetServiseDocumentTask();
				getServiseDocumentTask.execute();
			} else {
				InternetLockFragment ilf = new InternetLockFragment();
				FragmentManager fm = getSupportFragmentManager();
				FragmentTransaction ft = fm.beginTransaction();
				ft.addToBackStack(null);
				ft.add(android.R.id.content, ilf).commit();
			}
		} else{
			startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://oauth.yandex.ru/authorize?response_type=token&client_id=ed49b67ef91547279d33378569039264&display=popup")));
			finish();
		}
	}
	
	public void startPhotoPreview(Uri photoUri) {
		PreviewPhotoFragment pvf = PreviewPhotoFragment.newInstance(photoUri);
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction ft = fm.beginTransaction();
		ft.addToBackStack(null);
		ft.add(android.R.id.content, pvf,"preview").commit();
	}
	
	public String getPath(Uri uri) {
		String result = "";
		if(uri.toString().contains("content:/")){
		    String[] projection = { MediaStore.Images.Media.DATA };
		    Cursor cursor = managedQuery(uri, projection, null, null, null);
		    int column_index = cursor
		            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		    cursor.moveToFirst();
		    result =cursor.getString(column_index); 
		} else if(uri.toString().contains("file://")){
			result = uri.toString().substring(6);
		}
	    return result;
	}
	
	public void uploadPhoto(File img, String id, String title, String description) {
		yapi.uploadPhoto(img,id,title,description);
	}
	
	private class GetServiseDocumentTask extends ServerRequest {
		

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			List<NameValuePair> headers = new ArrayList<NameValuePair>();
			headers.add(new BasicNameValuePair("Authorization", "OAuth "+yapi.getToken()));
			method = HTTPMethod.buildGET("http://api-fotki.yandex.ru/api/me/", headers);
		}
		
		@Override
		protected void onPostExecute(Document result) {
			//super.onPostExecute(result);
			yapi.setPhotoAndAlbumsLinks(result);
			yapi.downloadAlbums();
			
			TakePhotoFragment tpf = new TakePhotoFragment();
			FragmentManager fm = getSupportFragmentManager();
			FragmentTransaction ft = fm.beginTransaction();
			Fragment dialog = fm.findFragmentByTag("dialog");
			ft.remove(dialog);
//			ft.addToBackStack(null);
			ft.add(android.R.id.content,tpf,"take").commit();
			
//			initViews();
		}
		
	}
	
	public void startAddOptionsFragment() {
		AddOptionsFragment aof = new AddOptionsFragment();
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction ft = fm.beginTransaction();
		ft.addToBackStack(null);
		ft.add(android.R.id.content, aof, "add_options").commit();
	}
	
	public void startCreateAlbumFragment() {
		CreateAlbumFragment caf = new CreateAlbumFragment();
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction ft = fm.beginTransaction();
		ft.addToBackStack(null);
		ft.add(android.R.id.content, caf).commit();
	}
	
	private boolean checkConnection() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
		if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) {
            return true;

        }
		return false;
	}
	
	//final int PROGRESS_DLG_ID = 666;
	private YaPreferences yaPrefs;
	private YandexAPI yapi;
}
